package org.jeecg.modules.paycenter.service;
import org.jeecg.modules.wlhy.bill.service.*;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.utils.BankPayUtil;
import org.jeecg.modules.wlhy.utils.R;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.PayConstants;
import org.jeecg.modules.paycenter.channel.constant.CommonConstants;
import org.jeecg.modules.paycenter.channel.zzbank.entity.HyZzbankAccount;
import org.jeecg.modules.paycenter.channel.zzbank.service.IHyZzbankAccountService;
import org.jeecg.modules.paycenter.channel.zzbank.util.SnowFlakeUtil;
import org.jeecg.modules.paycenter.channel.zzbank.vo.AllocateVo;
import org.jeecg.modules.paycenter.channel.zzbank.vo.WithdrawalVo;
import org.jeecg.modules.paycenter.dto.BatchPayDto;
import org.jeecg.modules.paycenter.dto.PayDto;
import org.jeecg.modules.paycenter.enums.UTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.wlhy.bill.entity.*;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hyplatform.entity.HyPlatformCost;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.company.service.IHyCompanyService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyplatform.service.IHyPlatformCostService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static org.jeecg.common.constant.PayConstants.BILL_TYPE.PAY_FREIGHT;
import static org.jeecg.common.constant.PayConstants.SHIPPING_PAY_STATUS.FAIL_PAY;
import static org.jeecg.modules.paycenter.enums.PayChannelEnum.ZHENGZHOU;

@Service
@Slf4j
public class ZhengZhouPayServiceImpl implements ZhengZhouPayService{
    @Resource
    private IHyShippingNoteService shippingNoteService;

    @Resource
    private IHyCustomerService customerService;

    @Resource
    private IHyCompanyService companyService;

    @Resource
    private IHyDriverService hyDriverService;

    @Resource
    private IHyVehicleService hyVehicleService;

    @Resource
    private IHyCarrierService carrierService;

    @Resource
    private IHyCustomerBillService customerBillService;

    @Resource
    private IHyShippingNoteBillService shippingNoteBillService;

    @Resource
    private IHyCarrierBillService carrierBillService;

    @Resource
    private IHyDriverBillService driverBillService;

    @Resource
    private IHySettingService settingService;

    @Resource
    private IHyPlatformCostService platformCostService;


    @Resource
    private IHyDriverBankService driverBankService;

    @Resource
    private IHyBillService hyBillService;
    
    @Resource
    private IHyZzbankAccountService zzbankAccountService;

    @Resource
    private IHyCaptainBillService hyCaptainBillService;

    @Resource
    private IHyCaptainService hyCaptainService;

    /**
     * 验证运单信息
     *
     * @param hyShippingNote
     * @param payDto
     * @param req
     * @return
     */
    @Override
    public R checkOrderInfo(HyShippingNote hyShippingNote, PayDto payDto, HttpServletRequest req) {
        if (hyShippingNote == null) {
            return R.failed("该运单不存在");
        }

        if(!BankPayUtil.checkSetting()) {
            return R.failed("系统支付功能暂时未开启");
        }

        if (!BankPayUtil.checkPwd(payDto.getUid(), payDto.getPw())) {
            return R.failed("支付密码错误");
        }
        //检查支付渠道
        if (!ZHENGZHOU.channelType.equalsIgnoreCase(payDto.getPayChannel())) {
            return R.failed("支付渠道不存在");
        }
        if (!BankPayUtil.checkOrderMode(hyShippingNote.getOrderMode())) {
            return R.failed("订单模式不正确");
        }

        if (!BankPayUtil.checkPayType(hyShippingNote.getPayType())) {
            return R.failed("支付方式不正确");
        }
        if (!checkAmount(hyShippingNote)) {
            return R.failed("运费金额不合法");
        }
        HyCustomer customerInfo = new HyCustomer();
        if (0 == payDto.getOperateType()) { //货主支付
            customerInfo = customerService.getCustomer(req);
        } else if (2 == payDto.getOperateType()){ //平台代付
            customerInfo = customerService.getById(hyShippingNote.getCustomerId());
        } else {
            customerInfo = customerService.getById(payDto.getCustomerId());
        }
        if (customerInfo == null || !hyShippingNote.getCustomerId().equalsIgnoreCase(customerInfo.getId())) {
            return R.failed("货主信息有误");
        }
        //如果是代理人支付需要验证代理人信息
        if (3 ==payDto.getOperateType()) {
            if (!hyShippingNote.getAgentId().equalsIgnoreCase(customerInfo.getId())) {
                return R.failed("经纪人信息有误");
            }
        }

        if(PayConstants.PAY_TYPE.BY_PREPAY.equals(hyShippingNote.getPayType())){
            if(!PayConstants.PREPAY_ORDER_STATUS.COMPLETE_PAY.equals(hyShippingNote.getPrePayStatus())  && !PayConstants.PREPAY_ORDER_STATUS.CONFIRM_PAY.equals(hyShippingNote.getPrePayStatus())){
                return R.failed(hyShippingNote.getShippingNoteNumber() + "预付运费未支付完成,不能支付");
            }
        }



        if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(hyShippingNote.getOrderMode())) {
            String agentId = hyShippingNote.getAgentId();
            if(StrUtil.isEmpty(agentId)){
                return R.failed("经纪人信息不存在");
            }
        }
        return R.ok();
    }

    /**
     * @param shippingNoteList
     * @param batchPayDto
     * @return
     */
    @Override
    public R checkPlateBatchPayOrderInfo(List<HyShippingNote> shippingNoteList, BatchPayDto batchPayDto) {
        if(!BankPayUtil.checkSetting()) {
            return R.failed("系统支付功能暂时未开启");
        }

        if (!BankPayUtil.checkPwd(batchPayDto.getUid(), batchPayDto.getPw())) {
            return R.failed("支付密码错误");
        }
        //检查支付渠道
        if (!ZHENGZHOU.channelType.equalsIgnoreCase(batchPayDto.getPayChannel())) {
            return R.failed("支付渠道不存在");
        }

        return R.ok();
    }

    /**
     * 检查平台支付相关信息
     *
     * @param shippingNoteList
     * @param batchPayDto
     * @param repayFlag
     * @return
     */
    @Override
    public R checkPlateAccountInfo(List<HyShippingNote> shippingNoteList, BatchPayDto batchPayDto, boolean repayFlag) {
        log.info("平台垫付开始验证账户信息");
        HyZzbankAccount accountInfo = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, "1")
                .one();
        if (ObjUtil.isEmpty(accountInfo)) {
            return R.failed("平台子账号未开通");
        }

        //校验货主资金账号余额
        if (!repayFlag) {//重新支付不再判断货主余额
            if (!checkAvailableForPlatePayBatch(accountInfo, shippingNoteList)) {
                return R.failed("平台垫付余额不足请充值！");
            }
        }

        List<String> driverIdList = shippingNoteList.stream().map(HyShippingNote::getDriverId).distinct().collect(Collectors.toList());
        List<String> carrierIdList = shippingNoteList.stream().filter(item->{
            return PayConstants.PAY_TYPE.BY_CARRIER.equalsIgnoreCase(item.getPayType());
        }).map(HyShippingNote::getCarrierId).distinct().collect(Collectors.toList());
        //验证司机，车队长的资金账号
        List<HyZzbankAccount> driverAccount = zzbankAccountService.lambdaQuery()
                .in(HyZzbankAccount::getUid, driverIdList)
                .list();
        //如果size不相等，说明有人没有开通资金账号
        if(driverAccount.size() != driverIdList.size()) {
            List<String> driverIdWithAccount=driverAccount.stream().map(HyZzbankAccount::getUid)
                    .distinct().collect(Collectors.toList());
            //求差集
            List<String> badIds = (List<String>) CollUtil.subtract(driverIdList, driverIdWithAccount);
            List<HyDriver> badDriverList = hyDriverService.lambdaQuery().in(HyDriver::getId, badIds).list();
            String driverNames = badDriverList.stream().map(HyDriver::getDriverName).collect(Collectors.joining(","));

            return R.failed("司机:"+driverNames+",未开通资金账号, 请开通后再发起支付");

        }
        //如果没有车队长则不用验证
        if (CollUtil.isNotEmpty(carrierIdList)) {
            log.info("开始进行车队长账号的验证");
            List<HyZzbankAccount> carrierAccount = zzbankAccountService.lambdaQuery()
                    .in(HyZzbankAccount::getUid, carrierIdList)
                    .list();
            //如果size不相等，说明有人没有开通资金账号
            if (carrierAccount.size() != carrierIdList.size()) {
                List<String> carrierIdWithAccount = carrierAccount.stream().map(HyZzbankAccount::getUid)
                        .distinct().collect(Collectors.toList());
                //求差集
                List<String> badCarrierIds = (List<String>) CollUtil.subtract(carrierIdList, carrierIdWithAccount);
                List<HyCarrier> badCarrierList = carrierService.lambdaQuery().in(HyCarrier::getId, badCarrierIds).list();
                String carrierNames = badCarrierList.stream().map(HyCarrier::getCarrierName).collect(Collectors.joining(","));
                return R.failed("车队长:"+carrierNames+",未开通资金账号, 请开通后再发起支付");
            }
        }
        return R.ok("批量支付账户校验通过");
    }


    /**
     * 平台单笔支付账号校验
     *
     * @param hyShippingNote
     * @param payDto
     * @return
     */
    @Override
    public R checkPlateAccountInfoPaySingle(HyShippingNote hyShippingNote, PayDto payDto, boolean repayFlag) {
        HyZzbankAccount plateAccount = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, "1")
                .one();
        if (ObjUtil.isEmpty(plateAccount)) {
            return R.failed("平台子账号未开通");
        }
        //检查司机信息
        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());
        if (ObjUtil.isEmpty(driver)) {
            return R.failed("司机信息不存在");
        } else {
            HyZzbankAccount driverAccountBook = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, driver.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.DRIVER.uType).one();
            //验证司机账号信息
            if (driverAccountBook == null) {
                return R.failed("司机尚未开通钱包功能,不能支付!");
            }
        }
        //检查载具信息
        HyVehicle vehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
        if (vehicle == null) {
            return R.failed("车辆信息不存在");
        }
        //检查货主相关信息
        HyCustomer customer = customerService.getById(hyShippingNote.getCustomerId());
        if (ObjUtil.isEmpty(customer)) {
            return R.failed("货主不存在");
        }

        //如果车队长信息存在，则校验检查车队长的相关信息
        if (ObjUtil.isNotEmpty(hyShippingNote.getCarrierId())) {
            HyCarrier carrier = carrierService.getById(hyShippingNote.getCarrierId());
            if (ObjUtil.isEmpty(carrier)) {
                return R.failed("车队长信息不存在");
            }
            //检查车队长钱包
            HyZzbankAccount carrierAccount =zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, carrier.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CARRIER.uType).one();
            //验证司机账号信息
            if (ObjUtil.isEmpty(carrierAccount)) {
                return R.failed("车队长尚未开通钱包功能,不能支付!");
            }
        }
        //验证承运商钱包
        if ("1".equals(hyShippingNote.getIzCaptainShipping())) {
            //验证承运商钱包
            HyCaptain captain = hyCaptainService.getById(hyShippingNote.getCaptainId());
            if (ObjUtil.isEmpty(captain)) {
                return R.failed("承运商信息不存在");
            } else {
                HyZzbankAccount captainAccount = zzbankAccountService.lambdaQuery()
                        .eq(HyZzbankAccount::getUid, captain.getId())
                        .eq(HyZzbankAccount::getUtype, UTypeEnum.CAPTAIN.uType).one();
                //验证承运商钱包
                if (ObjUtil.isEmpty(captainAccount)) {
                    return R.failed("承运商钱包不存在");
                }
            }
        }

        log.info("-------平台垫付开始校验资金是否够用-------------");
        if (!repayFlag && !checkAvailableForPlatePay(plateAccount, hyShippingNote)) {
            return R.failed("平台资金不足无法支付运单！");
        }

        return R.ok();
    }

    /**
     * 平台支付批量修改运单的支付状态
     *
     * @param hyShippingNote
     * @param loginUser
     * @param pateFormCostId
     * @return
     */
    @Override
    public boolean modifyShippingNoteForPlatePay(HyShippingNote hyShippingNote, SysUser loginUser, String pateFormCostId) {
        String realName = loginUser.getRealname();
        if (ObjUtil.isEmpty(realName)) {
            realName = loginUser.getPhone();
        }
        hyShippingNote.setFkr(realName);//设置付款人
        hyShippingNote.setShippingPayStatus(PayConstants.SHIPPING_PAY_STATUS.APPLY_PAY);
        hyShippingNote.setPayDt(new Date());//运费提交支付时间
        hyShippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.COMPANY_TO_DRIVER);//开始支付,因为平台支付是平台-》司机 ，所以状态应该是2
        hyShippingNote.setPayChannel(ZHENGZHOU.channelType);
        hyShippingNote.setPaySource(PayConstants.PAY_SOURCE.PLATFORM_PAY);
        hyShippingNote.setPlatformCostId(pateFormCostId);

        return shippingNoteService.updateById(hyShippingNote);
    }

    /**
     * 平台创建各种流水单
     *
     * @param hyShippingNote
     * @return
     */
    @Override
    public boolean createStatementForPlatePay(HyShippingNote hyShippingNote) {
        HyZzbankAccount plateAccount = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, "1")
                .one();

        HyZzbankAccount driverAccountBook = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, hyShippingNote.getDriverId())
                .eq(HyZzbankAccount::getUtype, UTypeEnum.DRIVER.uType)
                .one();

        if (ObjUtil.isEmpty(driverAccountBook)) {
            throw new RuntimeException("司机未开通郑州银行钱包，请开通钱包后再去支付");
        }


        //添加运单支付流水单,分公司到司机
        HyShippingNoteBill shippingNoteBill = this.createShippingBill(hyShippingNote);

        shippingNoteBill.setDbaccno(plateAccount.getSubAccount());
        shippingNoteBill.setDbaccname(plateAccount.getSubAccountName());
        shippingNoteBill.setDblogaccno("");
        shippingNoteBill.setDbProv("");
        //添加公司支付司机流水单
        shippingNoteBill.setCraccno(driverAccountBook.getSubAccount());
        shippingNoteBill.setCraccname(driverAccountBook.getSubAccountName());
        shippingNoteBill.setCrlogaccno("");
        shippingNoteBill.setCrProv("");
        shippingNoteBill.setBankCode("ZZBK");

        shippingNoteBillService.save(shippingNoteBill);

        //添加司机流水单
        HyDriverBill driverBill = this.createDriverBill(hyShippingNote, shippingNoteBill);
        driverBill.setDbaccno(plateAccount.getSubAccount());
        driverBill.setDbaccname(plateAccount.getSubAccountName());
        driverBill.setDblogaccno("");
        driverBill.setCraccno(driverAccountBook.getSubAccount());
        driverBill.setCraccname(driverAccountBook.getSubAccountName());
        driverBill.setCrlogaccno("");

        driverBillService.save(driverBill);
        //运费支付方式(1按运单结算2车队长结算)
        HyCarrierBill carrierBill = null;
        String payType = hyShippingNote.getPayType();
        if (PayConstants.PAY_TYPE.BY_ORDER.equals(payType) || PayConstants.PAY_TYPE.BY_PREPAY.equals(payType)) {
            driverBill.setBillType(PAY_FREIGHT);//司机支付运费
        } else {
            driverBill.setBillType(PayConstants.BILL_TYPE.PAY_CARRIER);//车队长代收
            HyZzbankAccount carrierAccountBook = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, hyShippingNote.getCarrierId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CARRIER.uType)
                    .one();
            if (ObjUtil.isEmpty(carrierAccountBook)) {
                throw new RuntimeException("车队长资金账号未开通！");
            }

            String carrierAccNo = carrierAccountBook.getSubAccount();
            String carrierAccName = carrierAccountBook.getSubAccountName();

            carrierBill = this.createCarrierBill(hyShippingNote);
            carrierBill.setDbaccno(driverAccountBook.getSubAccount());
            carrierBill.setDbaccname(driverAccountBook.getSubAccountName());
            carrierBill.setDblogaccno("");
            carrierBill.setDbProv("");
            carrierBill.setCraccno(carrierAccNo);
            carrierBill.setCraccname(carrierAccName);
            carrierBill.setCrlogaccno("");
            carrierBill.setCrBankCode("");
            carrierBillService.save(carrierBill);
        }

        if ("1".equals(hyShippingNote.getIzCaptainShipping())) {//如果是承运商运单
            HyCaptainBill hyCaptainBill = null;
            HyZzbankAccount captainAccount = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, hyShippingNote.getCaptainId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CAPTAIN.uType)
                    .one();
            String carrierAccNo = captainAccount.getSubAccount();
            String carrierAccName = captainAccount.getSubAccountName();

            hyCaptainBill = this.createCaptainBill(hyShippingNote);
            hyCaptainBill.setDbaccno(driverAccountBook.getSubAccount());
            hyCaptainBill.setDbaccname(driverAccountBook.getSubAccountName());
            hyCaptainBill.setCraccno(carrierAccNo);
            hyCaptainBill.setCraccname(carrierAccName);
            hyCaptainBillService.save(hyCaptainBill);

        }
        return true;
    }

    /**
     * 平台支付创建流水单
     *
     * @param shippingNoteList
     * @return
     */
    @Override
    public HyPlatformCost createPlateStatement(List<HyShippingNote> shippingNoteList) {
        HyPlatformCost platformCost = new HyPlatformCost();
        //默认列表中第一个customer
        platformCost.setCustomerId(shippingNoteList.get(0).getCustomerId());
        platformCost.setCustomerBillNums(shippingNoteList.size());
        platformCost.setSt("0");
        platformCost.setPayChannel(ZHENGZHOU.channelType);
        platformCost.setAmt(this.getTotalAmt(shippingNoteList));
        if (platformCostService.save(platformCost)) {
            return platformCost;
        } else {
            return null;
        }
    }

    /**
     * 平台支付创建流水单
     *
     * @param shippingNote
     * @return
     */
    @Override
    public HyPlatformCost createPlateStatement(HyShippingNote shippingNote, SysUser loginUser) {
        HyPlatformCost platformCost = new HyPlatformCost();
        //默认列表中第一个customer
        platformCost.setCustomerId(shippingNote.getCustomerId());
        platformCost.setCustomerBillNums(1);
        platformCost.setSt("0");
        platformCost.setPayChannel(ZHENGZHOU.channelType);
        platformCost.setCreateBy(loginUser.getUsername());
        platformCost.setUpdateBy(loginUser.getUsername());

        BigDecimal totalAmt = new BigDecimal("0");
        if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(shippingNote.getOrderMode())) {
            totalAmt = totalAmt.add(shippingNote.getAgentCostPayTotal());
        }else if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(shippingNote.getOrderMode()))  {
            totalAmt = totalAmt.add(shippingNote.getCostPayTotal());
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(shippingNote.getOrderMode())) {
            totalAmt = shippingNote.getCustomerPrice();
        }
        platformCost.setAmt(totalAmt);
        if (platformCostService.save(platformCost)) {
            return platformCost;
        } else {
            return null;
        }
    }

    /**
     * 批量支付订单信息验证
     *
     * @param shippingNoteList
     * @param batchPayDto
     * @return
     */
    @Override
    public R checkBatchPayOrderInfo(List<HyShippingNote> shippingNoteList, BatchPayDto batchPayDto, HttpServletRequest req) {
        String customerId = null;
        if(!BankPayUtil.checkSetting()) {
            return R.failed("系统支付功能暂时未开启");
        }

        if (!BankPayUtil.checkPwd(batchPayDto.getUid(), batchPayDto.getPw())) {
            return R.failed("支付密码错误");
        }
        //检查支付渠道
        if (!ZHENGZHOU.channelType.equalsIgnoreCase(batchPayDto.getPayChannel())) {
            return R.failed("支付渠道不存在");
        }


        List<String> customerIdList = shippingNoteList.stream().map(HyShippingNote::getCustomerId)
                .distinct().collect(Collectors.toList());
        if(customerIdList.size()>1) {
            return R.failed("不是同一个货主不能支付");
        }
        for (HyShippingNote hyShippingNote: shippingNoteList) {
            //预付运费信息校验
            if(PayConstants.PAY_TYPE.BY_PREPAY.equals(hyShippingNote.getPayType())){
                if(!PayConstants.PREPAY_ORDER_STATUS.COMPLETE_PAY.equals(hyShippingNote.getPrePayStatus())  && !PayConstants.PREPAY_ORDER_STATUS.CONFIRM_PAY.equals(hyShippingNote.getPrePayStatus())){
                    return R.failed(hyShippingNote.getShippingNoteNumber() + "预付运费未支付完成,不能支付");
                }
            }
            if (!PayConstants.SHIPPING_PAY_STATUS.COMPLETE_APPROVAL.equals(hyShippingNote.getShippingPayStatus())) {
                return R.failed(hyShippingNote.getShippingNoteNumber(),"未审核通过,不能支付!");
            }
            //如果是支付中提示支付中
            if (PayConstants.SHIPPING_PAY_STATUS.APPLY_PAY.equals(hyShippingNote.getShippingPayStatus())) {
                return R.failed(hyShippingNote.getShippingNoteNumber(),"支付中，不能重复支付!");
            }
            //验证公司
            HyCompany company = companyService.getById(hyShippingNote.getCompanyId());
            if (ObjUtil.isEmpty(company)) {
                return R.failed(hyShippingNote.getShippingNoteNumber(),"公司信息有误");
            }
            //验证支付方式
            if (!BankPayUtil.checkPayType(hyShippingNote.getPayType())) {
                return R.failed(hyShippingNote.getShippingNoteNumber(),"支付方式不正确");
            }
            //验证运单管理模式
            if (!BankPayUtil.checkOrderMode(hyShippingNote.getOrderMode())) {
                return R.failed(hyShippingNote.getShippingNoteNumber(),"运单管理模式错误");
            }
//            //验证司机，车辆，车队长信息
//            HyDriver hyDriver = hyDriverService.getById(hyShippingNote.getDriverId());
//            if (ObjUtil.isEmpty(hyDriver)) {
//                return R.failed(hyShippingNote.getShippingNoteNumber(),"司机信息异常");
//            }
//
//            HyVehicle hyVehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
//            if (ObjUtil.isEmpty(hyVehicle)) {
//                return R.failed(hyShippingNote.getShippingNoteNumber(),"车辆信息异常");
//            }
//            if (ObjUtil.isNotEmpty(hyShippingNote.getCarrierId())) {
//                Carrier carrier = carrierService.getById(hyShippingNote.getCarrierId());
//                if(ObjUtil.isEmpty(carrier)) {
//                    return R.failed(hyShippingNote.getShippingNoteNumber(),"车队长信息异常");
//                }
//            }
        }

//        //货主批量支付需要验证经纪人信息
//        if (1==batchPayDto.getOperateType()) {
//            Customer agentInfo = customerService.getCustomer(loginUser);
//            if (agentInfo == null) {
//                return R.failed("经纪人信息为空");
//            }
//        }
        //货主批量支付customerId通过登录用户获取customer, 系统批量支付的货主信息从运单上面取
        if(1==batchPayDto.getOperateType()) { //货主批量支付
            HyCustomer customer = customerService.getCustomer(req);
            return R.ok(customer.getId(),"货主批量支付运单校验通过");
        } else {
            return R.ok(customerIdList.get(0),"系统批量支付运单校验通过");
        }


    }

    /**
     * 货主批量支付验证账户信息
     *
     * @param hyShippingNoteList
     * @param customer
     * @return
     */
    @Override
    public R checkAccountInfoBath(List<HyShippingNote> hyShippingNoteList, HyCustomer customer, boolean repayFlag) {
        HyZzbankAccount customerAccount = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, customer.getId())
                .eq(HyZzbankAccount::getUtype, UTypeEnum.CUSTOMER.uType)
                .one();
        if (ObjUtil.isEmpty(customerAccount)) {
            return R.failed("货主资金账号未开通");
        }
        //校验货主资金账号余额
        if (!repayFlag) {//重新支付不再判断货主余额
            if (!checkAvailableForBatch(customerAccount, hyShippingNoteList)) {
                return R.failed("货主余额不足请充值！");
            }
        }


        List<String> driverIdList = hyShippingNoteList.stream().map(HyShippingNote::getDriverId).distinct().collect(Collectors.toList());
        List<String> carrierIdList = hyShippingNoteList.stream().filter(item->{
            return PayConstants.PAY_TYPE.BY_CARRIER.equalsIgnoreCase(item.getPayType());
        }).map(HyShippingNote::getCarrierId).distinct().collect(Collectors.toList());

        //验证司机，车队长的资金账号
        List<HyZzbankAccount> driverAccount = zzbankAccountService.lambdaQuery()
                .in(HyZzbankAccount::getUid, driverIdList)
                .list();
        //如果size不相等，说明有人没有开通资金账号
        if(driverAccount.size() != driverIdList.size()) {
            List<String> driverIdWithAccount = driverAccount.stream().map(HyZzbankAccount::getUid)
                    .distinct().collect(Collectors.toList());
            //求差集
            List<String> badIds = (List<String>) CollUtil.subtract(driverIdList, driverIdWithAccount);
            List<HyDriver> badDriverList = hyDriverService.lambdaQuery().in(HyDriver::getId, badIds).list();
            String driverNames = badDriverList.stream().map(HyDriver::getDriverName).collect(Collectors.joining(","));

            return R.failed("司机:"+driverNames+",未开通资金账号, 请开通后再发起支付");

        }
        //如果车队长的list不为空
        if (CollUtil.isNotEmpty(carrierIdList)) {
            List<HyZzbankAccount> carrierAccount = zzbankAccountService.lambdaQuery()
                    .in(HyZzbankAccount::getUid, carrierIdList)
                    .list();
            //如果size不相等，说明有人没有开通资金账号
            if (carrierAccount.size() != carrierIdList.size()) {
                List<String> carrierIdWithAccount = carrierAccount.stream().map(HyZzbankAccount::getUid)
                        .distinct().collect(Collectors.toList());
                //求差集
                List<String> badCarrierIds = (List<String>) CollUtil.subtract(carrierIdList, carrierIdWithAccount);
                List<HyCarrier> badCarrierList = carrierService.lambdaQuery().in(HyCarrier::getId, badCarrierIds).list();
                String carrierNames = badCarrierList.stream().map(HyCarrier::getCarrierName).collect(Collectors.joining(","));
                return R.failed("车队长:"+carrierNames+",未开通资金账号, 请开通后再发起支付");
            }
        }

        return R.ok("批量支付账户校验通过");
    }

    /**
     * 检查支付账号相关信息
     *
     * @param hyShippingNote
     * @return
     */
    @Override
    public R checkAccountInfo(HyShippingNote hyShippingNote,  boolean repayFlag) {
        //检查公司信息
        HyCompany company = companyService.getById(hyShippingNote.getCompanyId());
        if (company == null) {
            return  R.failed("公司信息不存在");
        } else {
            //检查分公司钱包
            HyZzbankAccount companyAccountBook = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, "1")
                    .one();
            if (ObjUtil.isEmpty(companyAccountBook)) {
                return R.failed("分公司尚未开通钱包功能!");
            }

        }
        //检查司机信息
        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());
        if (driver == null) {
            return R.failed("司机信息不存在");
        } else {
            HyZzbankAccount driverAccountBook = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, driver.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.DRIVER.uType).one();
            //验证司机账号信息
            if (ObjUtil.isEmpty(driverAccountBook)) {
                return R.failed("司机尚未开通钱包功能,不能支付!");
            }
        }
        //检查载具信息
        HyVehicle vehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
        if (vehicle == null) {
            return R.failed("车辆信息不存在");
        }
        //检查货主相关信息
        HyCustomer customer = customerService.getById(hyShippingNote.getCustomerId());
        if (ObjUtil.isEmpty(customer)) {
            return R.failed("货主不存在");
        }
        //检查货主的钱包功能
        HyZzbankAccount customerAccountBook = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, customer.getId())
                .eq(HyZzbankAccount::getUtype, UTypeEnum.CUSTOMER.uType).one();
        if (ObjUtil.isNull(customerAccountBook)) {
            return R.failed("货主尚未开通钱包功能!");
        }
        //如果车队长信息存在，则校验检查车队长的相关信息
        if (ObjUtil.isNotEmpty(hyShippingNote.getCarrierId())) {
            HyCarrier carrier = carrierService.getById(hyShippingNote.getCarrierId());
            if (ObjUtil.isEmpty(carrier)) {
                return R.failed("车队长信息不存在");
            }
            //检查车队长钱包
            HyZzbankAccount carrierAccount =zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, carrier.getId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CARRIER.uType).one();
            //验证司机账号信息
            if (ObjUtil.isEmpty(carrierAccount)) {
                return R.failed("车队长尚未开通钱包功能,不能支付!");
            }
        }
        //验证承运商钱包
        if ("1".equals(hyShippingNote.getIzCaptainShipping())) {
            //验证承运商钱包
            HyCaptain captain = hyCaptainService.getById(hyShippingNote.getCaptainId());
            if (ObjUtil.isEmpty(captain)) {
                return R.failed("承运商信息不存在");
            } else {
                HyZzbankAccount captainAccount = zzbankAccountService.lambdaQuery()
                        .eq(HyZzbankAccount::getUid, captain.getId())
                        .eq(HyZzbankAccount::getUtype, UTypeEnum.CAPTAIN.uType).one();
                //验证承运商钱包
                if (ObjUtil.isEmpty(captainAccount)) {
                   return R.failed("承运商钱包不存在");
                }
            }
        }

        if (!repayFlag) {//重新支付不再判断货主余额
            if (!checkAvailable(customerAccountBook, hyShippingNote)) {
                return R.failed("货主余额不足请充值！");
            }
        }
        return R.ok();
    }

    public boolean checkAvailable(HyZzbankAccount accountInfo, HyShippingNote shippingNote) {
        //查询清分账户余额
        String balanceAmt = zzbankAccountService.subAccountInfoByAccNo(accountInfo.getSubAccount());
        BigDecimal costPayTotal = null;//运费合计（运费+服务费），货主支付给分公
        String orderMode = shippingNote.getOrderMode();
        if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
            costPayTotal = shippingNote.getCostPayTotal();//运费合计（运费+服务费），货主支付给分公
        }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
            costPayTotal = shippingNote.getAgentCostPayTotal();//经纪人模式
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
            costPayTotal = shippingNote.getCustomerPrice();
        }
        BigDecimal available = new BigDecimal(balanceAmt);
        return NumberUtil.isGreaterOrEqual(available, costPayTotal);
    }


    /**
     * 批量支付校验账户余额
     * @param accountInfo
     * @param shippingNoteList
     * @return
     */
    public boolean checkAvailableForBatch(HyZzbankAccount accountInfo, List<HyShippingNote> shippingNoteList) {
        //查询清分账户余额
        String balanceAmt = zzbankAccountService.subAccountInfoByAccNo(accountInfo.getSubAccount());
        BigDecimal totalAmt = new BigDecimal("0");
        for (HyShippingNote shippingNote: shippingNoteList) {
            BigDecimal costPayTotal = new BigDecimal("0");;//运费合计（运费+服务费），货主支付给分公
            String orderMode = shippingNote.getOrderMode();
            if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
                costPayTotal = shippingNote.getCostPayTotal();//运费合计（运费+服务费），货主支付给分公
            }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
                costPayTotal = shippingNote.getAgentCostPayTotal();//经纪人模式
            } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
                costPayTotal = shippingNote.getCustomerPrice();
            }
            totalAmt = totalAmt.add(costPayTotal);
        }
        return NumberUtil.isGreaterOrEqual(new BigDecimal(balanceAmt), totalAmt);
    }


    /**
     * 平台垫付校验金额
     * @param accountInfo
     * @param shippingNote
     * @return
     */

    public boolean checkAvailableForPlatePay(HyZzbankAccount accountInfo, HyShippingNote shippingNote) {
        //查询清分账户余额
        String balanceAmt = zzbankAccountService.subAccountInfoByAccNo(accountInfo.getSubAccount());
        BigDecimal costPayTotal = null;//运费合计（运费+服务费），货主支付给分公
        String orderMode = shippingNote.getOrderMode();
        if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
            costPayTotal = shippingNote.getCostPayShipping();//运费 平台支付给司机
        }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
            costPayTotal = shippingNote.getCostPayShipping();//经纪人模式
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
            costPayTotal = shippingNote.getCustomerPrice();
        }

        return NumberUtil.isGreaterOrEqual(new BigDecimal(balanceAmt), costPayTotal);
    }

    /**
     * 平台批量待付账户余额校验
     * @param accountInfo
     * @param shippingNoteList
     * @return
     */

    public boolean checkAvailableForPlatePayBatch(HyZzbankAccount accountInfo, List<HyShippingNote> shippingNoteList) {
        //查询清分账户余额
        String balanceAmt = zzbankAccountService.subAccountInfoByAccNo(accountInfo.getSubAccount());

        BigDecimal totalAmt = new BigDecimal("0");

        for (HyShippingNote shippingNote: shippingNoteList) {
            BigDecimal costPayTotal = new BigDecimal("0");//运费合计（运费+服务费），货主支付给分公
            String orderMode = shippingNote.getOrderMode();
            if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
                costPayTotal = shippingNote.getCostPayShipping();//运费 平台支付给司机
            }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
                costPayTotal = shippingNote.getCostPayShipping();//经纪人模式
            } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
                costPayTotal = shippingNote.getCustomerPrice();
            }
            totalAmt = totalAmt.add(costPayTotal);
        }


        return NumberUtil.isGreaterOrEqual(new BigDecimal(balanceAmt), totalAmt);
    }


    /**
     * 检查支付的运费金额是否合法
     * @param shippingNote
     * @return
     */
    public boolean checkAmount(HyShippingNote shippingNote) {
        BigDecimal costPayTotal = new BigDecimal("0");//运费合计（运费+服务费），货主支付给分公
        String orderMode = shippingNote.getOrderMode();
        if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
            costPayTotal = shippingNote.getCostPayTotal();//运费合计（运费+服务费），货主支付给分公
        } else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
            costPayTotal = shippingNote.getAgentCostPayTotal();//经纪人模式
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
            costPayTotal = shippingNote.getCustomerPrice();
        }
        return NumberUtil.isGreater(costPayTotal, new BigDecimal("0"));
    }

    /**
     * 修改运单状态未支付中
     *
     * @param hyShippingNote
     * @return
     */
    @Override
    public boolean modifyShippingNotePayInfo(HyShippingNote hyShippingNote, SysUser loginUser) {
        String realName = loginUser.getRealname();
        if (ObjUtil.isEmpty(realName)) {
            realName = loginUser.getPhone();
        }
        hyShippingNote.setFkr(realName);//设置付款人
        hyShippingNote.setShippingPayStatus(PayConstants.SHIPPING_PAY_STATUS.APPLY_PAY);
        hyShippingNote.setPayDt(new Date());//运费提交支付时间
        hyShippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.CUSTOMER_TO_COMPANY);//开始支付 1
        hyShippingNote.setPayChannel(ZHENGZHOU.channelType);
        hyShippingNote.setPaySource(PayConstants.PAY_SOURCE.ACCOUNT_PAY);
        return shippingNoteService.updateById(hyShippingNote);
    }

    /**
     * 重新支付前修改运单的状态为支付中
     *
     * @param hyShippingNote
     * @param loginUser
     * @return
     */
    @Override
    public boolean modifyShippingNoteRePayInfo(HyShippingNote hyShippingNote, SysUser loginUser) {
        String realName = loginUser.getRealname();
        if (ObjUtil.isEmpty(realName)) {
            realName = loginUser.getPhone();
        }
        hyShippingNote.setFkr(realName);//设置付款人
        hyShippingNote.setShippingPayStatus(PayConstants.SHIPPING_PAY_STATUS.APPLY_PAY);
        hyShippingNote.setPayDt(new Date());//运费提交支付时间
        return shippingNoteService.updateById(hyShippingNote);
    }

    /**
     * 更新HY_BILL表
     *
     * @param shippingNote
     * @return
     */
    @Override
    public boolean updateHyBill(HyShippingNote shippingNote) {
        log.info("---开始----保存hybill信息----");
        HyBill billInfo = hyBillService.lambdaQuery()
                .eq(HyBill::getShippingId, shippingNote.getId())
                .eq(HyBill::getDelFlag, "0")
                .eq(HyBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setAgentId(StrUtil.isNotEmpty(shippingNote.getAgentId())?shippingNote.getAgentId():"");
        //平台垫付没有货主的流水信息
        if (!shippingNote.getPaySource().equalsIgnoreCase(PayConstants.PAY_SOURCE.PLATFORM_PAY)) {
            HyCustomerBill customerBill = customerBillService.lambdaQuery()
                    .eq(HyCustomerBill::getShippingId, shippingNote.getId())
                    .eq(HyCustomerBill::getDelFlag, "0")
                    .eq(HyCustomerBill::getBillType, PAY_FREIGHT)
                    .one();
            billInfo.setCustomerBillId(customerBill.getId());
        }

        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setShippingBillId(shippingNoteBill.getId());
        HyDriverBill driverBill = driverBillService.lambdaQuery()
                .eq(HyDriverBill::getShippingId, shippingNote.getId())
                .eq(HyDriverBill::getDelFlag, "0")
                .eq(HyDriverBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setDriverBillId(driverBill.getId());
        if (PayConstants.PAY_TYPE.BY_CARRIER.equalsIgnoreCase(shippingNote.getPayType())) { //如果是车队长支付需要保存车队长的流水单
            HyCarrierBill carrierBill = carrierBillService.lambdaQuery()
                    .eq(HyCarrierBill::getShippingId, shippingNote.getId())
                    .eq(HyCarrierBill::getDelFlag, "0")
                    .eq(HyCarrierBill::getBillType, PAY_FREIGHT)
                    .one();
            billInfo.setCarrierBillId(carrierBill.getId());
        }
        billInfo.setPayChannel(ZHENGZHOU.channelType);
        billInfo.setPaySource(shippingNote.getPaySource());
        billInfo.setPayStatus(PayConstants.SHIPPING_PAY_STATUS.COMPLETE_PAY);
        billInfo.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);
        billInfo.setPayDt(new Date());
        boolean R = hyBillService.updateById(billInfo);
        log.info("---结束----保存hybill信息----结果状态:"+R);
        return  R;
    }

    /**
     * 支付失败更新HY_BILL表
     *
     * @param shippingNote
     * @return
     */
    @Override
    public boolean updateHyBillForFail(HyShippingNote shippingNote) {
        HyBill billInfo = hyBillService.lambdaQuery()
                .eq(HyBill::getShippingId, shippingNote.getId())
                .eq(HyBill::getDelFlag, "0")
                .eq(HyBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setPayChannel(shippingNote.getPayChannel());
        billInfo.setBillPayStatus(shippingNote.getBillPayStatus());
        billInfo.setPayStatus(FAIL_PAY);
        billInfo.setPaySource(shippingNote.getPaySource());
        //支付失败状态设置成7
        return hyBillService.updateById(billInfo);
    }

    /**
     * 平台代付更新
     *
     * @param shippingNote
     * @param platformCost
     * @return
     */
    @Override
    public boolean updateHyBillForPlatePay(HyShippingNote shippingNote, HyPlatformCost platformCost) {
        log.info("---开始----保存hybill信息----");
        HyBill billInfo = hyBillService.lambdaQuery()
                .eq(HyBill::getShippingId, shippingNote.getId())
                .eq(HyBill::getDelFlag, "0")
                .eq(HyBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setAgentId(StrUtil.isNotEmpty(shippingNote.getAgentId())?shippingNote.getAgentId():"");
        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setShippingBillId(shippingNoteBill.getId());
        HyDriverBill driverBill = driverBillService.lambdaQuery()
                .eq(HyDriverBill::getShippingId, shippingNote.getId())
                .eq(HyDriverBill::getDelFlag, "0")
                .eq(HyDriverBill::getBillType, PAY_FREIGHT)
                .one();
        billInfo.setDriverBillId(driverBill.getId());
        if (PayConstants.PAY_TYPE.BY_CARRIER.equalsIgnoreCase(shippingNote.getPayType())) { //如果是车队长支付需要保存车队长的流水单
            HyCarrierBill carrierBill = carrierBillService.lambdaQuery()
                    .eq(HyCarrierBill::getShippingId, shippingNote.getId())
                    .eq(HyCarrierBill::getDelFlag, "0")
                    .eq(HyCarrierBill::getBillType, PAY_FREIGHT)
                    .one();
            billInfo.setCarrierBillId(carrierBill.getId());
        }
        billInfo.setDfId(platformCost.getId());
        billInfo.setPayChannel(ZHENGZHOU.channelType);
        billInfo.setPaySource(shippingNote.getPaySource());
        billInfo.setPayStatus(PayConstants.SHIPPING_PAY_STATUS.COMPLETE_PAY);
        billInfo.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);
        billInfo.setPayDt(new Date());
        boolean R = hyBillService.updateById(billInfo);
        log.info("---结束----保存hybill信息----结果状态:"+R);
        return  R;
    }

    /**
     * 支付流
     * 资金流向分为两个流程
     * 1、货主->平台->司机
     * 2、货主->平台->司机->车队长
     *
     * @param shippingNote
     * @return
     */
    @Override
    public R payActivity(HyShippingNote shippingNote) {
        log.info("---------------正常支付流程开始-------------");
        // 1 货主支付 2 公司支付给司机 3 司机支付给车队长   8 流程完成
        //4司机自动提现银行卡
        if(PayConstants.BILL_PAY_STATUS.CUSTOMER_TO_COMPANY.equals(shippingNote.getBillPayStatus())) {
            //1货主支付给公司
            log.info("---------------1、货主支付--start-----------"+shippingNote.getShippingNoteNumber());
            if (CommonConstants.FAIL == customerToCompany(shippingNote).getCode()) {
                log.info("---------------1、货主支付--fail-----------");
                return R.failed(shippingNote.getShippingNoteNumber(),"货主支付给公司，信息验证失败");
            }
            log.info("---------------1、货主支付--success-----------"+shippingNote.getShippingNoteNumber());
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.COMPANY_TO_DRIVER);
            shippingNoteService.updateById(shippingNote);
        }


        //2 公司支付给司机
        log.info("---------------2、公司支付给司机--start-----------"+shippingNote.getShippingNoteNumber());
        if(PayConstants.BILL_PAY_STATUS.COMPANY_TO_DRIVER.equals(shippingNote.getBillPayStatus())) {
            if (CommonConstants.FAIL == payToDriver(shippingNote).getCode()) {
                log.info("---------------2、公司支付给司机--fail-----------"+shippingNote.getShippingNoteNumber());
                return R.failed(shippingNote.getShippingNoteNumber(),"公司支付给司机，信息验证失败");
            }
            log.info("---------------2、公司支付给司机--success-----------"+shippingNote.getShippingNoteNumber());
            //按运单结算
            if(PayConstants.PAY_TYPE.BY_ORDER.equals(shippingNote.getPayType()) || PayConstants.PAY_TYPE.BY_PREPAY.equals(shippingNote.getPayType())) {
                if(StringUtils.isNotEmpty(shippingNote.getDriverBankId())) {
                    if("1".equals(settingService.lambdaQuery()
                            .like(HySetting::getTag, "autotx").one().getData())){
                        shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.DRIVER_CASH_OUT);//司机自动提现
                        log.info("---------------2、公司支付给司机-司机自动提现-success-----------"+shippingNote.getShippingNoteNumber());

                    }else {
                        log.info("---------------2、公司支付给司机-司机没有自动提现-success-----------"+shippingNote.getShippingNoteNumber());
                        shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
                    }
                }else {
                    shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
                    log.info("---------------2、公司支付给司机-司机没有银行卡信息-success-----------"+shippingNote.getShippingNoteNumber());

                }
                //按车队长结算
            }else if (PayConstants.PAY_TYPE.BY_CARRIER.equals(shippingNote.getPayType()) || "1".equals(shippingNote.getIzCaptainShipping())) {
                log.info("---------------2、公司支付给司机-设置车队长代收状态-success-----------"+shippingNote.getShippingNoteNumber());
                shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.DRIVER_TO_CARRIER);//车队长代收
            }else {
                shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
                log.info("---------------2、公司支付给司机-其他支付模式-success-----------"+shippingNote.getShippingNoteNumber());
            }
            log.info("---------------2、公司支付给司机-流程完毕-success-----------"+shippingNote.getShippingNoteNumber());
            shippingNoteService.updateById(shippingNote);
        }

        //3 车队长代收
        log.info("---------------3、车队长代收-start-----------"+shippingNote.getShippingNoteNumber());
        //向车队长支付时金额必须大于0
        if(PayConstants.BILL_PAY_STATUS.DRIVER_TO_CARRIER.equals(shippingNote.getBillPayStatus())
                && NumberUtil.isGreater(shippingNote.getCarrierFee(), BigDecimal.valueOf(0))
                && !"1".equals(shippingNote.getIzCaptainShipping())) {
            if (CommonConstants.FAIL == driverToCarrier(shippingNote).getCode()) {
                log.info("---------------3、车队长代收-fail-----------"+shippingNote.getShippingNoteNumber());
                return R.failed(shippingNote.getShippingNoteNumber(),"车队长代收校验失败");
            }
            log.info("---------------3、车队长代收-success-----------"+shippingNote.getShippingNoteNumber());
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
            shippingNoteService.updateById(shippingNote);
        }
        //3.1承运商收款
        if(NumberUtil.isGreater(shippingNote.getCaptainFee(), BigDecimal.valueOf(0))
                && "1".equals(shippingNote.getIzCaptainShipping())) {
            if (CommonConstants.FAIL == driverToCaptain(shippingNote).getCode()) {
                log.info("---------------3、承运商代收-fail-----------"+shippingNote.getShippingNoteNumber());
                return R.failed(shippingNote.getShippingNoteNumber(),"承运商代收校验失败");
            }
            log.info("---------------3、承运商代收-success-----------"+shippingNote.getShippingNoteNumber());
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
            shippingNoteService.updateById(shippingNote);
        }

        //4 司机提现
        log.info("---------------4、司机提现-start-----------"+shippingNote.getShippingNoteNumber());
        if(PayConstants.BILL_PAY_STATUS.DRIVER_CASH_OUT.equals(shippingNote.getBillPayStatus())) {
            //异步司机自动提现
            CompletableFuture.supplyAsync(() -> {
                try {
                    driverTX(shippingNote);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return "异步司机自动提现";
            });

            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
        }
        log.info("---------------5、支付流程完成-----------"+shippingNote.getShippingNoteNumber());

        //更新支付完成状态
        shippingNote.setShippingPayStatus(PayConstants.SHIPPING_PAY_STATUS.COMPLETE_PAY);//运单支付完成
        //shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
        shippingNote.setBillPayRemark("");
        shippingNoteService.updateById(shippingNote);
        return R.ok(shippingNote.getShippingNoteNumber(),"支付成功");

    }

    /**
     * 平台代付
     *
     *  平台-》司机
     *  平台-》司机-》车队长
     * @param shippingNote
     * @return
     */
    @Override
    public R platePayActivity(HyShippingNote shippingNote) {
        log.info("---------------平台代付开始-------------");
        //支付给司机
        if(PayConstants.BILL_PAY_STATUS.COMPANY_TO_DRIVER.equals(shippingNote.getBillPayStatus())) {
            if (CommonConstants.FAIL == payToDriver(shippingNote).getCode()) {
                return R.failed(shippingNote.getShippingNoteNumber(),"平台支付给司机，信息验证失败");
            }
            //按运单结算
            if(PayConstants.PAY_TYPE.BY_ORDER.equals(shippingNote.getPayType()) || PayConstants.PAY_TYPE.BY_PREPAY.equals(shippingNote.getPayType())) {
                if(StringUtils.isNotEmpty(shippingNote.getDriverBankId())) {
                    if("1".equals(settingService.lambdaQuery()
                            .like(HySetting::getTag, "autotx").one().getData())){
                        shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.DRIVER_CASH_OUT);//司机自动提现
                    }else {
                        shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
                    }
                }else {
                    shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
                }
                //按车队长结算
            }else if (PayConstants.PAY_TYPE.BY_CARRIER.equals(shippingNote.getPayType()) || "1".equals(shippingNote.getIzCaptainShipping())) {
                shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.DRIVER_TO_CARRIER);//车队长代收
            }else {
                shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
            }
            shippingNoteService.updateById(shippingNote);
        }

        //3 车队长代收
        if(PayConstants.BILL_PAY_STATUS.DRIVER_TO_CARRIER.equals(shippingNote.getBillPayStatus())
                && NumberUtil.isGreater(shippingNote.getCarrierFee(), BigDecimal.valueOf(0))
                && !"1".equals(shippingNote.getIzCaptainShipping())) {
            if (CommonConstants.FAIL == driverToCarrier(shippingNote).getCode()) {
                return R.failed(shippingNote.getShippingNoteNumber(),"车队长代收校验失败");
            }
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
            shippingNoteService.updateById(shippingNote);
        }

        //4 承运商代收
        if(NumberUtil.isGreater(shippingNote.getCaptainFee(), BigDecimal.valueOf(0))
                && "1".equals(shippingNote.getIzCaptainShipping())) {
            if (CommonConstants.FAIL == driverToCaptain(shippingNote).getCode()) {
                return R.failed(shippingNote.getShippingNoteNumber(),"承运商代收校验失败");
            }
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
            shippingNoteService.updateById(shippingNote);
        }
        //4 司机提现
        if(PayConstants.BILL_PAY_STATUS.DRIVER_CASH_OUT.equals(shippingNote.getBillPayStatus())) {
            //异步司机自动提现
            CompletableFuture.supplyAsync(() -> {
                try {
                    driverTX(shippingNote);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return "异步司机自动提现";
            });
            shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
        }

        //更新支付完成状态
        shippingNote.setShippingPayStatus(PayConstants.SHIPPING_PAY_STATUS.COMPLETE_PAY);//运单支付完成
        //shippingNote.setBillPayStatus(PayConstants.BILL_PAY_STATUS.FLOW_END);//流程完成
        shippingNote.setBillPayRemark("");
        shippingNoteService.updateById(shippingNote);
        return R.ok(shippingNote.getShippingNoteNumber(),"支付成功");
    }

    /**
     * 司机提现
     * @param shippingNote
     */
    private R driverTX(HyShippingNote shippingNote) throws Exception {
        HyDriver driver =  hyDriverService.getById(shippingNote.getDriverId());
        //验证卡号
        HyDriverBank driverBank = driverBankService.getById(shippingNote.getDriverBankId());
        if(driverBank == null){
            return R.failed("未获取到银行卡信息！");
        }
        if(!StringUtils.equals(driverBank.getDriverId() ,driver.getId())){
            return R.failed("银行卡信息错误！");
        }
        //校验是否是本人银行卡
        if("1".equals(settingService.lambdaQuery()
                .like(HySetting::getTag, "self_bankcard")
                .one().getData())) {
            if (!driverBank.getBankName().equalsIgnoreCase(driver.getDriverName())) {
                log.info("不是本人银行卡禁止提现");
                return R.failed("不是本人银行卡禁止提现");
            }
        }
        HyZzbankAccount driverAccount = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, driver.getId())
                .one();

        WithdrawalVo transferVo = new WithdrawalVo();
        transferVo.setRemark("司机提现");
        transferVo.setBankCode(driverBank.getCrBankNo());
        transferVo.setPayeeAcNo(driverBank.getBankNum());
        transferVo.setPayeeBankName(driverBank.getBankName());
        transferVo.setPayerAcNo(driverAccount.getSubAccount());
        transferVo.setPayerAcName(driverAccount.getSubAccountName());
        transferVo.setTransAmt(shippingNote.getCostPayShipping().toString());
        transferVo.setErpJnlNo(SnowFlakeUtil.nextId().toString());
        Map<String, String> rMap = zzbankAccountService.transfer(transferVo);

        HyDriverBill driverBill = new HyDriverBill();
        driverBill.setBillNum(transferVo.getErpJnlNo());//交易请求流水号
        driverBill.setBillType(PayConstants.BILL_TYPE.CASH_OUT);//提现
        driverBill.setDriverId(driver.getId());
        driverBill.setDbaccno(driverAccount.getSubAccount());
        driverBill.setDbaccname(driverAccount.getSubAccountName());
        driverBill.setDblogaccno("");
        driverBill.setCraccno(driverBank.getBankNum());
        driverBill.setCraccname(driverBank.getBankName());
        driverBill.setCrlogaccno("");
        driverBill.setAmt(shippingNote.getCostPayShipping()); //提现金额
        driverBill.setRespSource(CommonConstants.SUCCESS.toString());
        if ("OK".equals(rMap.get("processState"))) {
            driverBill.setFrontFlowNo(rMap.get("transJnl"));
            driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
            driverBill.setRespInfo(rMap.get("processState")+"交易成功");
            driverBill.setRespSource(CommonConstants.SUCCESS.toString());
            driverBill.setPayChannel(ZHENGZHOU.channelType);
            driverBillService.save(driverBill);
            return R.ok(shippingNote.getShippingNoteNumber(),"司机自动提现成功");
        } else {
            driverBill.setRespSource("-1");
            driverBill.setRespCode("-1");
            driverBill.setRespInfo("接收交易数据超时,请查询交易状态"+rMap.get("processState"));
            driverBillService.save(driverBill);
            return R.failed(shippingNote.getShippingNoteNumber(),"司机自动提现失败");
        }

    }

    /**
     * 司机到车队长
     * @param shippingNote
     * @return
     */
    private R driverToCarrier(HyShippingNote shippingNote) {
        log.info("start-------------------司机到车队长，运单号为："+shippingNote.getShippingNoteNumber());

        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();

        HyCarrierBill carrierBill = carrierBillService.lambdaQuery()
                .eq(HyCarrierBill::getShippingId, shippingNote.getId())
                .eq(HyCarrierBill::getDelFlag, "0")
                .eq(HyCarrierBill::getBillType, PAY_FREIGHT)
                .one();

        if(CommonConstants.SUCCESS.toString().equals(carrierBill.getRespSource())){
            log.info("success-------------------司机到车队长，运单号为："+shippingNote.getShippingNoteNumber());
            return R.ok(shippingNote.getShippingNoteNumber(),"司机到车队长交易成功");
        }

        //重新支付的情况
        if(PayConstants.BANK_PAY_SOUR.FAIL.equalsIgnoreCase(carrierBill.getRespSource())) {
            R resetR = reSetShippingNoteBill(shippingNoteBill);
            //如果更新失败，则返回失败原因
            if (CommonConstants.FAIL == resetR.getCode()) {
                return resetR;
            } else {
                R resetCarrierBill = reSetCarrierBill(carrierBill);
                if (CommonConstants.FAIL == resetR.getCode()) {
                    return resetCarrierBill;
                }
            }
        }

        //支付
        if (StringUtils.isEmpty(carrierBill.getRespSource())) {
            try {

                BigDecimal costPayShipping = carrierBill.getAmt();//实际运费

                //司机支付给车队长
                AllocateVo allocateVo = new AllocateVo();
                allocateVo.setPayAcNo(carrierBill.getDbaccno()); //付款方子账号
                allocateVo.setPutAcNo(carrierBill.getCraccno()); //收款方子账号
                allocateVo.setTransAmt(costPayShipping.toString());
                allocateVo.setRemark("司机支付给车队长");
                allocateVo.setErpJnlNo(SnowFlakeUtil.nextId().toString());
                shippingNoteBill.setBillNum(allocateVo.getErpJnlNo());
                Map<String, String> rMap = zzbankAccountService.allocateTransfer(allocateVo);
                if("OK".equals(rMap.get("processState"))){
                    shippingNoteBill.setRespSource(CommonConstants.SUCCESS.toString());
                    shippingNoteBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    shippingNoteBill.setRespInfo(rMap.get("processState")+"交易成功");
                    shippingNoteBill.setFrontFlowNo(rMap.get("transJnl"));

                    carrierBill.setRespSource(CommonConstants.SUCCESS.toString());
                    carrierBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    carrierBill.setRespInfo(rMap.get("processState")+"交易成功");
                    carrierBill.setFrontFlowNo(rMap.get("transJnl"));
                    //保存信息
                    if (carrierBillService.updateById(carrierBill) &&  shippingNoteBillService.updateById(shippingNoteBill)) {
                        log.info("success-------------------司机到车队长，运单号为："+shippingNote.getShippingNoteNumber());
                        return R.ok(shippingNote.getShippingNoteNumber(),"司机到车队长交易成功");
                    }
                } else {
                    String statusCode = "E90003";
                    carrierBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    carrierBill.setRespCode(statusCode);
                    carrierBill.setRxtInfo("司机到车队长支付失败");

                    shippingNoteBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    shippingNoteBill.setRespCode(statusCode);
                    shippingNoteBill.setRxtInfo("司机到车队长支付失败");
                    log.error("failed-------------------司机到车队长，运单号为,"+shippingNote.getShippingNoteNumber());
                }
            } catch (Exception e) {
                carrierBill.setRespSource("-1");
                carrierBill.setRespCode("-1");
                carrierBill.setRespInfo(e.getMessage());
                carrierBill.setRxtInfo("");

                shippingNoteBill.setRespSource("5");
                shippingNoteBill.setRespCode("-1");
                shippingNoteBill.setRespInfo("-1");
                shippingNoteBill.setRxtInfo("司机到车队长支付失败");
                log.error("failed-------------------司机到车队长，运单号为,"+shippingNote.getShippingNoteNumber());
                shippingNote.setBillPayRemark("未知错误，需人工处理，" + e.getMessage());
            }
        }
        carrierBillService.updateById(carrierBill);
        shippingNoteBillService.updateById(shippingNoteBill);
        return R.failed(shippingNote.getShippingNoteNumber(), "司机到车队长交易失败");
    }


    /**
     * 承运商支付运费
     * @param shippingNote
     * @return
     */
    private R driverToCaptain(HyShippingNote shippingNote) {
        log.info("start-------------------司机到承运商，运单号为："+shippingNote.getShippingNoteNumber());
        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();

        HyCaptainBill captainBill = hyCaptainBillService.lambdaQuery()
                .eq(HyCaptainBill::getShippingId, shippingNote.getId())
                .eq(HyCaptainBill::getDelFlag, "0")
                .eq(HyCaptainBill::getBillType, PAY_FREIGHT)
                .one();

        if(CommonConstants.SUCCESS.toString().equals(captainBill.getRespSource())){
            log.info("success-------------------司机到承运商，运单号为："+shippingNote.getShippingNoteNumber());
            return R.ok(shippingNote.getShippingNoteNumber(),"司机到车队长交易成功");
        }

        //重新支付的情况
        if(PayConstants.BANK_PAY_SOUR.FAIL.equalsIgnoreCase(captainBill.getRespSource())) {
            R resetR = reSetShippingNoteBill(shippingNoteBill);
            //如果更新失败，则返回失败原因
            if (CommonConstants.FAIL == resetR.getCode()) {
                return resetR;
            } else {
                R resetCarrierBill = reSetCaptianBill(captainBill);
                if (CommonConstants.FAIL == resetR.getCode()) {
                    return resetCarrierBill;
                }
            }
        }

        //支付
        if (StringUtils.isEmpty(captainBill.getRespSource())) {
            try {

                BigDecimal costPayShipping = captainBill.getAmt();//实际运费
                //司机支付给承运商
                AllocateVo allocateVo = new AllocateVo();
                allocateVo.setPayAcNo(captainBill.getDbaccno()); //付款方子账号
                allocateVo.setPutAcNo(captainBill.getCraccno()); //收款方子账号
                allocateVo.setTransAmt(costPayShipping.toString());
                allocateVo.setRemark("司机支付给承运商");
                allocateVo.setErpJnlNo(SnowFlakeUtil.nextId().toString());
                shippingNoteBill.setBillNum(allocateVo.getErpJnlNo());
                Map<String, String> rMap = zzbankAccountService.allocateTransfer(allocateVo);
                if("OK".equals(rMap.get("processState"))){
                    shippingNoteBill.setRespSource(CommonConstants.SUCCESS.toString());
                    shippingNoteBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    shippingNoteBill.setRespInfo(rMap.get("processState")+"交易成功");
                    shippingNoteBill.setFrontFlowNo(rMap.get("transJnl"));

                    captainBill.setRespSource(CommonConstants.SUCCESS.toString());
                    captainBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    captainBill.setRespInfo(rMap.get("processState")+"交易成功");
                    captainBill.setFrontFlowNo(rMap.get("transJnl"));
                    //保存信息
                    if (hyCaptainBillService.updateById(captainBill) &&  shippingNoteBillService.updateById(shippingNoteBill)) {
                        log.info("success-------------------司机到承运商，运单号为："+shippingNote.getShippingNoteNumber());
                        return R.ok(shippingNote.getShippingNoteNumber(),"司机到承运商交易成功");
                    }
                } else {
                    String statusCode = "E90003";
                    captainBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    captainBill.setRespCode(statusCode);
                    captainBill.setRxtInfo("司机到承运商支付失败");

                    shippingNoteBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    shippingNoteBill.setRespCode(statusCode);
                    shippingNoteBill.setRxtInfo("司机到承运商支付失败");
                    log.error("failed-------------------司机到承运商，运单号为,"+shippingNote.getShippingNoteNumber());
                }
            } catch (Exception e) {
                captainBill.setRespSource("-1");
                captainBill.setRespCode("-1");
                captainBill.setRespInfo(e.getMessage());
                captainBill.setRxtInfo("");

                shippingNoteBill.setRespSource("5");
                shippingNoteBill.setRespCode("-1");
                shippingNoteBill.setRespInfo("-1");
                shippingNoteBill.setRxtInfo("司机到承运商支付失败");
                log.error("failed-------------------司机到承运商，运单号为,"+shippingNote.getShippingNoteNumber());
                shippingNote.setBillPayRemark("未知错误，需人工处理，" + e.getMessage());
            }
        }
        hyCaptainBillService.updateById(captainBill);
        shippingNoteBillService.updateById(shippingNoteBill);
        return R.failed(shippingNote.getShippingNoteNumber(), "司机到承运商交易失败");
    }


    /**
     * 公司到司机
     * @param shippingNote
     * @return
     */
    private R payToDriver(HyShippingNote shippingNote) {
        log.info("start-------------------向司机支付，运单号为："+shippingNote.getShippingNoteNumber());
        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();
        HyDriverBill driverBill = driverBillService.lambdaQuery()
                .eq(HyDriverBill::getShippingId, shippingNote.getId())
                .eq(HyDriverBill::getDelFlag, "0")
                .eq(HyDriverBill::getBillType, PAY_FREIGHT)
                .one();


        if(CommonConstants.SUCCESS.toString().equals(driverBill.getRespSource())){
            log.info("success-------------------公司到司机，运单号为："+shippingNote.getShippingNoteNumber());
            return R.ok(shippingNote.getShippingNoteNumber(), "公司到司机支付成功");
        }
        //重新支付的情况
        if(PayConstants.BANK_PAY_SOUR.FAIL.equalsIgnoreCase(driverBill.getRespSource())) {
            R resetR = reSetShippingNoteBill(shippingNoteBill);
            //如果更新失败，则返回失败原因
            if (CommonConstants.FAIL == resetR.getCode()) {
                return resetR;
            } else {
                R resetDriverBill = reSetDriverBill(driverBill);
                if (CommonConstants.FAIL == resetR.getCode()) {
                    return resetDriverBill;
                }
            }
        }
        log.info("运单：{}，开始向司机支付", shippingNote.getShippingNoteNumber());
        //支付
        if (StringUtils.isEmpty(driverBill.getRespSource())) {
            try {

                BigDecimal costPayShipping = shippingNote.getCostPayShipping();//实际运费，分公司支付给司机
                AllocateVo allocateVo = new AllocateVo();
                allocateVo.setErpJnlNo(SnowFlakeUtil.nextId().toString());
                allocateVo.setPayAcNo(shippingNoteBill.getDbaccno());
                allocateVo.setPutAcNo(shippingNoteBill.getCraccno());
                allocateVo.setTransAmt(costPayShipping.toString());
                allocateVo.setRemark("司机运费,运单号："+shippingNote.getShippingNoteNumber());
                Map<String, String> rMap = zzbankAccountService.allocateTransfer(allocateVo);
                if("OK".equals(rMap.get("processState"))){
                    if (PayConstants.PAY_TYPE.BY_ORDER.equalsIgnoreCase(shippingNote.getPayType()) || PayConstants.PAY_TYPE.BY_PREPAY.equals(shippingNote.getPayType())) {
                        log.info("按单支付-----流程完结");
                        shippingNoteBill.setRespSource(CommonConstants.SUCCESS.toString());
                        shippingNoteBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                        shippingNoteBill.setRespInfo(rMap.get("processState")+"交易成功");
                        shippingNoteBill.setFrontFlowNo(rMap.get("transJnl"));//交易成功时，保存内转交易流水号
                        shippingNoteBill.setBillNum(allocateVo.getErpJnlNo());
                        shippingNoteBillService.updateById(shippingNoteBill);
                    }


                    driverBill.setRespSource(CommonConstants.SUCCESS.toString());
                    driverBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS);
                    driverBill.setRespInfo(rMap.get("processState")+"交易成功");
                    driverBill.setFrontFlowNo(rMap.get("transJnl"));//交易成功时，保存内转交易流水号
                    driverBill.setBillNum(allocateVo.getErpJnlNo());// 三分交易流水号
                    if (driverBillService.updateById(driverBill)) {
                        log.info("success-------------------公司到司机，运单号为："+shippingNote.getShippingNoteNumber());
                        return R.ok(shippingNote.getShippingNoteNumber(), "公司到司机支付成功");
                    }
                }else {
                    log.info("failed-------------------公司到司机，运单号为："+shippingNote.getShippingNoteNumber());
                    String statusCode = "E90001";
                    driverBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    driverBill.setRespCode(statusCode);
                    driverBill.setRxtInfo("司机支付失败");

                    shippingNoteBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);
                    shippingNoteBill.setRespCode(statusCode);
                    shippingNoteBill.setRxtInfo("司机支付失败");
                    shippingNoteBillService.updateById(shippingNoteBill);
                    driverBillService.updateById(driverBill);
                }
            } catch (Exception e) {
                log.info("failed-------------------向司机，运单号为："+shippingNote.getShippingNoteNumber());
                driverBill.setRespSource("-1");
                driverBill.setRespCode("-1");
                driverBill.setRespInfo(e.getMessage());
                driverBill.setRxtInfo("平台到司机支付失败");

                shippingNoteBill.setRespSource("5");
                shippingNoteBill.setRespCode("-1");
                shippingNoteBill.setRespInfo(e.getMessage());
                shippingNoteBill.setRxtInfo("平台到司机支付失败");

                shippingNoteBillService.updateById(shippingNoteBill);
                driverBillService.updateById(driverBill);
                log.error("fail--未知错误，需人工处理-----------货主支付到平台，运单号为："+shippingNote.getShippingNoteNumber());
            }
        }
        log.info("fail-------------------货主支付到平台，运单号为："+shippingNote.getShippingNoteNumber());
        return R.failed(shippingNote.getShippingNoteNumber(), "公司到司机支付失败");
    }

    /**
     * 货主支付给公司
     * @param shippingNote
     * @return
     */
    private R customerToCompany(HyShippingNote shippingNote){
        log.info("start-------------------货主支付到平台，运单号为："+shippingNote.getShippingNoteNumber());
        HyCustomerBill customerBill = customerBillService.lambdaQuery()
                .eq(HyCustomerBill::getShippingId, shippingNote.getId())
                .eq(HyCustomerBill::getDelFlag, "0")
                .eq(HyCustomerBill::getBillType, PAY_FREIGHT)
                .one();
        HyShippingNoteBill shippingNoteBill = shippingNoteBillService.lambdaQuery()
                .eq(HyShippingNoteBill::getShippingId, shippingNote.getId())
                .eq(HyShippingNoteBill::getDelFlag, "0")
                .eq(HyShippingNoteBill::getBillType, PAY_FREIGHT)
                .one();

        if(CommonConstants.SUCCESS.toString().equals(customerBill.getRespSource())){
            return R.ok(shippingNote.getShippingNoteNumber(), "货主到平台支付成功");
        }
        //重新支付的情况
        if(PayConstants.BANK_PAY_SOUR.FAIL.equalsIgnoreCase(customerBill.getRespSource())) {
            R resetR = reSetCustomerBill(customerBill);
            //如果更新失败，则返回失败原因
            if (CommonConstants.FAIL == resetR.getCode()) {
                return resetR;
            }
        }
        //支付
        if (StringUtils.isEmpty(customerBill.getRespSource())) {
            try {
                BigDecimal costPayTotal = null;//运费合计（运费+服务费），货主支付给分公
                String orderMode = shippingNote.getOrderMode();
                if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
                    costPayTotal = shippingNote.getCostPayTotal();//运费合计（运费+服务费），货主支付给分公
                }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
                    costPayTotal = shippingNote.getAgentCostPayTotal();//经纪人模式
                } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
                    costPayTotal = shippingNote.getCustomerPrice();
                }
                //货主支付给分公司
                AllocateVo allocateVo = new AllocateVo();
                allocateVo.setRemark("货主支付运费，运单号： " + shippingNote.getShippingNoteNumber());
                allocateVo.setTransAmt(String.valueOf(costPayTotal));
                allocateVo.setPayAcNo(customerBill.getDbaccno());
                allocateVo.setPutAcNo(customerBill.getCraccno());
                allocateVo.setErpJnlNo(SnowFlakeUtil.nextId().toString());
                Map<String, String> rMap = zzbankAccountService.allocateTransfer(allocateVo);
                if ("OK".equals(rMap.get("processState"))) {
                    customerBill.setRespSource(CommonConstants.SUCCESS.toString()); //支付成功标志位
                    customerBill.setRespCode(PayConstants.BANK_PAY_SOUR.SUCCESS); //交易成功代码
                    customerBill.setRespInfo(rMap.get("processState")+"交易成功");
                    customerBill.setBillNum(allocateVo.getErpJnlNo());
                    customerBill.setFrontFlowNo(rMap.get("transJnl"));
                    //保存信息
                    if(customerBillService.updateById(customerBill)) {
                        log.info("success-------------------货主支付到平台，运单号为："+shippingNote.getShippingNoteNumber());
                        return  R.ok(shippingNote.getShippingNoteNumber(),"货主支付到平台成功");
                    }
                } else {
                    String statusCode = "E90002";
                    customerBill.setRespSource(PayConstants.BANK_PAY_SOUR.FAIL);//失败
                    customerBill.setRespCode(statusCode);
                    customerBill.setRxtInfo("交易失败");
                    customerBillService.updateById(customerBill);
                }
            } catch (Exception e) {
                customerBill.setRespSource("-1");
                customerBill.setRespCode("-1");
                customerBill.setRespInfo(e.getMessage());
                customerBill.setRxtInfo("");
                customerBillService.updateById(customerBill);


                //支付失败更新运单流水表
                shippingNoteBillService.lambdaUpdate()
                        .set(HyShippingNoteBill::getRespSource, "5")
                        .set(HyShippingNoteBill::getRespCode, "-1")
                        .set(HyShippingNoteBill::getRespInfo, e.getMessage())
                        .set(HyShippingNoteBill::getRxtInfo, "平台到司机支付失败")
                        .eq(HyShippingNoteBill::getId, shippingNoteBill.getId())
                        .update();

                log.error("未知错误，需人工处理, 运单号为："+shippingNote.getShippingNoteNumber());
            }
        }
        customerBillService.updateById(customerBill);
        log.info("fail-------------------货主支付到平台，运单号为："+shippingNote.getShippingNoteNumber());
        return R.failed(shippingNote.getShippingNoteNumber(),"货主支付到平台失败");

    }



    /**
     * 创建各种流水单
     *
     * @param hyShippingNote
     * @return
     */
    @Override
    @Transactional
    public boolean createStatement(HyShippingNote hyShippingNote) {
        HyZzbankAccount customerAccountBook = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, hyShippingNote.getCustomerId())
                .eq(HyZzbankAccount::getUtype, UTypeEnum.CUSTOMER.uType)
                .one();
        //平台公司清分账号
        HyZzbankAccount companyAccountBook = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, "1")
                .eq(HyZzbankAccount::getUtype, UTypeEnum.SYSUSER.uType)
                .one();
        HyZzbankAccount driverAccountBook = zzbankAccountService.lambdaQuery()
                .eq(HyZzbankAccount::getUid, hyShippingNote.getDriverId())
                .eq(HyZzbankAccount::getUtype, UTypeEnum.DRIVER.uType)
                .one();
        //货主钱包
        String customerDbAccNo = customerAccountBook.getSubAccount();
        String customerDbAccName = customerAccountBook.getSubAccountName();
        //分公司子账号
        String companyAccNo = companyAccountBook.getSubAccount();
        String companyAccName = companyAccountBook.getSubAccountName();

        String driverAccNo = driverAccountBook.getSubAccount();
        String driverAccName = driverAccountBook.getSubAccountName();

        HyCustomerBill customerBill = this.createCustomerBill(hyShippingNote);
        customerBill.setDbaccno(customerDbAccNo);
        customerBill.setDbaccname(customerDbAccName);
        customerBill.setDblogaccno("");
        customerBill.setDbProv("");
        customerBill.setCraccno(companyAccNo);
        customerBill.setCraccname(companyAccName);
        customerBill.setCrlogaccno("");
        customerBill.setCrProv("");

        customerBillService.save(customerBill);

        //添加运单支付流水单,分公司到司机
        HyShippingNoteBill shippingNoteBill = this.createShippingBill(hyShippingNote);
        //分公司
        shippingNoteBill.setDbaccno(companyAccNo);
        shippingNoteBill.setDbaccname(companyAccName);
        shippingNoteBill.setDblogaccno("");
        shippingNoteBill.setDbProv("");
        //添加公司支付司机流水单
        shippingNoteBill.setCraccno(driverAccNo);
        shippingNoteBill.setCraccname(driverAccName);
        shippingNoteBill.setCrlogaccno("");
        shippingNoteBill.setCrProv("");
        shippingNoteBill.setBankCode("ZZBK");

        shippingNoteBillService.save(shippingNoteBill);

        //添加司机流水单
        HyDriverBill driverBill = this.createDriverBill(hyShippingNote, shippingNoteBill);
        driverBill.setDbaccno(companyAccNo);
        driverBill.setDbaccname(companyAccName);
        driverBill.setDblogaccno("");
        driverBill.setCraccno(driverAccNo);
        driverBill.setCraccname(driverAccName);
        driverBill.setCrlogaccno("");

        driverBillService.save(driverBill);
        //运费支付方式(1按运单结算2车队长结算)
        HyCarrierBill carrierBill = new HyCarrierBill();
        String payType = hyShippingNote.getPayType();
        if (PayConstants.PAY_TYPE.BY_ORDER.equals(payType) || PayConstants.PAY_TYPE.BY_PREPAY.equals(payType)) {
            carrierBill.setBillType(PAY_FREIGHT);//司机支付运费
        } else {
            carrierBill.setBillType(PayConstants.BILL_TYPE.PAY_CARRIER);//车队长代收
            HyZzbankAccount carrierAccountBook = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, hyShippingNote.getCarrierId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CARRIER.uType)
                    .one();
            String carrierAccNo = carrierAccountBook.getSubAccount();
            String carrierAccName = carrierAccountBook.getSubAccountName();

            carrierBill = this.createCarrierBill(hyShippingNote);
            carrierBill.setDbaccno(driverAccNo);
            carrierBill.setDbaccname(driverAccName);
            carrierBill.setDblogaccno("");
            carrierBill.setDbProv("");
            carrierBill.setCraccno(carrierAccNo);
            carrierBill.setCraccname(carrierAccName);
            carrierBill.setCrlogaccno("");
            carrierBill.setCrBankCode("");
            carrierBillService.save(carrierBill);
        }

        if ("1".equals(hyShippingNote.getIzCaptainShipping())) {//如果是承运商运单
            HyCaptainBill hyCaptainBill = new HyCaptainBill();
            HyZzbankAccount captainAccount = zzbankAccountService.lambdaQuery()
                    .eq(HyZzbankAccount::getUid, hyShippingNote.getCaptainId())
                    .eq(HyZzbankAccount::getUtype, UTypeEnum.CAPTAIN.uType)
                    .one();
            String carrierAccNo = captainAccount.getSubAccount();
            String carrierAccName = captainAccount.getSubAccountName();

            hyCaptainBill = this.createCaptainBill(hyShippingNote);
            hyCaptainBill.setDbaccno(driverAccNo);
            hyCaptainBill.setDbaccname(driverAccName);
            hyCaptainBill.setCraccno(carrierAccNo);
            hyCaptainBill.setCraccname(carrierAccName);
            hyCaptainBillService.save(hyCaptainBill);

        }
        return true;
    }


    public HyCustomerBill createCustomerBill(HyShippingNote hyShippingNote){

        //添加货主支付公司流水单
        BigDecimal customerCostPayTotal = this.getCustomerCostPayTotal(hyShippingNote);//运费合计（运费+服务费），货主支付给分公司
        BigDecimal customerCostPayShipping = this.getCustomerCostPayShipping(hyShippingNote);

        HyCustomerBill customerBill = new HyCustomerBill();
        customerBill.setBillNum(SnowFlakeUtil.nextId().toString());//设置支付流水单
        customerBill.setBillType(PAY_FREIGHT);
        customerBill.setOrderId(hyShippingNote.getOrderId());
        customerBill.setShippingId(hyShippingNote.getId());
        customerBill.setCustomerId(hyShippingNote.getCustomerId());
        customerBill.setCompanyId(hyShippingNote.getCompanyId());

        customerBill.setAmt(customerCostPayTotal);//运费合计（运费+服务费），货主支付给分公司
        customerBill.setCostPayShipping(customerCostPayShipping);
        customerBill.setCostService(hyShippingNote.getCostService());
        customerBill.setPayChannel(hyShippingNote.getPayChannel());
        customerBill.setPaySource(hyShippingNote.getPaySource());
        customerBill.setPayDt(new Date());
        customerBill.setDelFlag("0");

        return customerBill;
    }

    public HyShippingNoteBill createShippingBill(HyShippingNote hyShippingNote) {
        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());
        HyVehicle vehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
        //添加运单支付流水单,分公司到司机
        HyShippingNoteBill shippingNoteBill = new HyShippingNoteBill();
        shippingNoteBill.setPayChannel(hyShippingNote.getPayChannel());
        shippingNoteBill.setBillNum(SnowFlakeUtil.nextId().toString());
        shippingNoteBill.setBillType(PAY_FREIGHT);
        shippingNoteBill.setOrderId(hyShippingNote.getOrderId());
        shippingNoteBill.setShippingId(hyShippingNote.getId());
        shippingNoteBill.setShippingNoteNumber(hyShippingNote.getShippingNoteNumber());
        shippingNoteBill.setCompanyId(hyShippingNote.getCompanyId());
        shippingNoteBill.setPayType(hyShippingNote.getPayType());
        shippingNoteBill.setCarrierId(hyShippingNote.getCarrierId());
        shippingNoteBill.setDriverId(hyShippingNote.getDriverId());
        shippingNoteBill.setCarrier(driver.getDriverName());
        shippingNoteBill.setActualCarrierId(driver.getIdcard());
        shippingNoteBill.setVehicleId(hyShippingNote.getVehicleId());
        shippingNoteBill.setVehicleNumber(vehicle.getVehicleNumber());
        shippingNoteBill.setVehicleColorCode(vehicle.getVehiclePlateColorCode());
        shippingNoteBill.setAmt(hyShippingNote.getCostPayShipping());//实际运费，分公司支付给司机
        shippingNoteBill.setPayDt(new Date());//支付时间
        shippingNoteBill.setDelFlag("0");
        return shippingNoteBill;
    }

    public HyDriverBill createDriverBill(HyShippingNote hyShippingNote,
                                       HyShippingNoteBill shippingNoteBill) {
        //添加司机流水单
        HyDriverBill driverBill = new HyDriverBill();
        driverBill.setBillNum(shippingNoteBill.getBillNum());//流水单号
        driverBill.setOrderId(hyShippingNote.getOrderId());
        driverBill.setCompanyId(hyShippingNote.getCompanyId());
        driverBill.setShippingId(hyShippingNote.getId());
        driverBill.setDriverId(hyShippingNote.getDriverId());
        driverBill.setAmt(hyShippingNote.getCostPayShipping()); //实际运费
        driverBill.setPayChannel(hyShippingNote.getPayChannel());
        driverBill.setBillType(PAY_FREIGHT);
        driverBill.setDelFlag("0");
        return driverBill;
    }

    /**
     * carrierFeeType车队长运费计算方式(0全部1按吨)
     * carrierFeeType = 0  全部 : 返回实付运费 costPayShipping
     * carrierFeeType = 1  按吨 : 返回车队长运费 carrierFee
     * carrierFeeType = 2  包车价 : 返回车队长运费 carrierFee
     * @param hyShippingNote
     * @return
     */
    public BigDecimal getCarrierBillAmt(HyShippingNote hyShippingNote) {
        //carrierFeeType车队长运费计算方式(0全部1按吨)
        if ("1".equals(hyShippingNote.getCarrierFeeType()) || "2".equals(hyShippingNote.getCarrierFeeType())) {
            return hyShippingNote.getCarrierFee();
        } else if ("2".equals(hyShippingNote.getCarrierFeeType())) {
            BigDecimal carrierFee = hyShippingNote.getCarrierFee();
            if (NumberUtil.isGreater(carrierFee, hyShippingNote.getCostPayShipping())) {
                carrierFee = hyShippingNote.getCostPayShipping();
            }
            return carrierFee;
        } else {
            return hyShippingNote.getCostPayShipping();
        }
    }

    public HyCarrierBill createCarrierBill(HyShippingNote hyShippingNote) {
        BigDecimal carrierFee = this.getCarrierBillAmt(hyShippingNote);
        HyCarrierBill carrierBill = new HyCarrierBill();
        carrierBill.setBillNum(SnowFlakeUtil.nextId().toString());
        carrierBill.setBillType(PAY_FREIGHT);
        carrierBill.setCarrierId(hyShippingNote.getCarrierId());
        carrierBill.setOrderId(hyShippingNote.getOrderId());
        carrierBill.setCompanyId(hyShippingNote.getCompanyId());
        carrierBill.setShippingId(hyShippingNote.getId());
        carrierBill.setDriverId(hyShippingNote.getDriverId());
        carrierBill.setAmt(carrierFee); //实际运费
        carrierBill.setPayChannel(hyShippingNote.getPayChannel());
        carrierBill.setDelFlag("0");
        return carrierBill;
    }

    public HyCaptainBill createCaptainBill(HyShippingNote hyShippingNote) {
        HyCaptainBill hyCaptainBill = new HyCaptainBill();
        hyCaptainBill.setBillNum(SnowFlakeUtil.nextId().toString());
        hyCaptainBill.setBillType(PAY_FREIGHT);
        hyCaptainBill.setCarrierId(hyShippingNote.getCarrierId());
        hyCaptainBill.setOrderId(hyShippingNote.getOrderId());
        hyCaptainBill.setCompanyId(hyShippingNote.getCompanyId());
        hyCaptainBill.setShippingId(hyShippingNote.getId());
        hyCaptainBill.setDriverId(hyShippingNote.getDriverId());
        hyCaptainBill.setAmt(hyShippingNote.getCaptainFee()); //实际运费
        hyCaptainBill.setPayChannel(hyShippingNote.getPayChannel());
        hyCaptainBill.setDelFlag("0");
        return hyCaptainBill;
    }


    public BigDecimal getCustomerCostPayTotal(HyShippingNote hyShippingNote){
        String orderMode = hyShippingNote.getOrderMode();
        //差价模式
        if (PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)) {
            return hyShippingNote.getAgentCostPayTotal();//运费合计
        } else if (PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)) {
            return hyShippingNote.getCostPayTotal();//运费合计（运费+服务费），货主支付给分公司
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equals(orderMode)) {
            return hyShippingNote.getCustomerPrice();
        } else {
            throw new RuntimeException("运单管理模式信息错误");
        }
    }

    public BigDecimal getCustomerCostPayShipping(HyShippingNote hyShippingNote){
        String orderMode = hyShippingNote.getOrderMode();
        //差价模式
        if (PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)) {
            return hyShippingNote.getAgentCostPayShipping();
        } else if (PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)) {
            return hyShippingNote.getCostPayShipping();
        } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equals(orderMode)) {
            return hyShippingNote.getCustomerPrice();
        } else {
            throw new RuntimeException("运单管理模式信息错误");
        }
    }

    /**
     * 获取运单总金额
     * @param hyShippingNotes
     * @return
     */
    public BigDecimal getTotalAmt(List<HyShippingNote> hyShippingNotes){
        BigDecimal totalAmt = new BigDecimal("0");

        for (HyShippingNote shippingNote: hyShippingNotes) {
            BigDecimal costPayTotal = new BigDecimal("0");//运费合计（运费+服务费），货主支付给分公
            String orderMode = shippingNote.getOrderMode();
            if(PayConstants.ORDER_MODE.MANAGE_FEE.equals(orderMode)){
                costPayTotal = shippingNote.getCostPayShipping();//运费 平台支付给司机
            }else if(PayConstants.ORDER_MODE.DIFF_PRICE.equals(orderMode)){
                costPayTotal = shippingNote.getCostPayShipping();//经纪人模式
            } else if (PayConstants.ORDER_MODE.CUSTOMER_MODE.equalsIgnoreCase(orderMode)) {
                costPayTotal = shippingNote.getCustomerPrice();
            }
            totalAmt = totalAmt.add(costPayTotal);
        }
        return totalAmt;
    }


    /**
     * 重置货主流水单
     * @param customerBill
     * @return
     */
    public R reSetCustomerBill(HyCustomerBill customerBill){
        if(customerBill==null){
            return R.failed("运费流水单信息不存在");
        }
        String respSource = customerBill.getRespSource();
        if (PayConstants.BANK_PAY_SOUR.FAIL.equals(respSource)) {
            String customerBillNum = CodeUtil.getBillNum(UTypeEnum.CUSTOMER);
            customerBill.setRespSource(null);
            customerBill.setBillNum(customerBillNum);
            customerBill.setPayDt(new Date());//支付时间
            customerBillService.updateById(customerBill);
            return R.ok("货主流水单重置成功");
        }
        return R.failed("货主流水单信息状态异常");
    }

    /**
     * 重置运单流水单
     * @param shippingNoteBill
     * @return
     */
    public R reSetShippingNoteBill(HyShippingNoteBill shippingNoteBill){
        if(shippingNoteBill==null){
            return R.failed("运费流水单信息不存在");
        }
        String respSource = shippingNoteBill.getRespSource();
        if (PayConstants.BANK_PAY_SOUR.FAIL.equals(respSource)) {
            String shippingNoteBillNum = CodeUtil.getBillNum(UTypeEnum.DRIVER);
            shippingNoteBill.setRespSource(null);
            shippingNoteBill.setBillNum(shippingNoteBillNum);
            shippingNoteBill.setPayDt(new Date());//支付时间
            shippingNoteBillService.updateById(shippingNoteBill);
            return R.ok("运单流水单信息重置成功");
        }
        return R.failed("运单流水状态异常");
    }

    /**
     * 重置车队长流水单
     * @param carrierBill
     * @return
     */

    protected R reSetCarrierBill(HyCarrierBill carrierBill) {
        if(carrierBill==null){
            return R.failed("运费流水单信息不存在");
        }
        String respSource = carrierBill.getRespSource();
        if (PayConstants.BANK_PAY_SOUR.FAIL.equals(respSource)) {
            String billNum = CodeUtil.getBillNum(UTypeEnum.CARRIER);
            carrierBill.setRespSource(null);
            carrierBill.setBillNum(billNum);
            carrierBillService.updateById(carrierBill);
            return R.ok("车队长流水单信息充值成功");
        }
        return R.failed("车队长流水单状态错误");
    }

    /**
     * 重置承运商支付流水表
     * @param captainBill
     * @return
     */

    protected R reSetCaptianBill(HyCaptainBill captainBill) {
        if(captainBill==null){
            return R.failed("运费流水单信息不存在");
        }
        String respSource = captainBill.getRespSource();
        if (PayConstants.BANK_PAY_SOUR.FAIL.equals(respSource)) {
            String billNum = CodeUtil.getBillNum(UTypeEnum.CARRIER);
            captainBill.setRespSource(null);
            captainBill.setBillNum(billNum);
            hyCaptainBillService.updateById(captainBill);
            return R.ok("车队长流水单信息充值成功");
        }
        return R.failed("车队长流水单状态错误");
    }



    /**
     * 重置司机流水单
     * @param driverBill
     * @return
     */

    protected R reSetDriverBill(HyDriverBill driverBill) {
        if(driverBill==null){
            return R.failed("运费流水单信息不存在");
        }
        String respSource = driverBill.getRespSource();
        if (PayConstants.BANK_PAY_SOUR.FAIL.equals(respSource)) {
            String billNum = CodeUtil.getBillNum(UTypeEnum.CARRIER);
            driverBill.setRespSource(null);
            driverBill.setBillNum(billNum);
            driverBillService.updateById(driverBill);
            return R.ok("司机流水单信息重置成功");
        }
        return R.failed("司机流水单状态错误");
    }

}
